using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;

namespace GameCore.UI
{
    public class ProgressBar : MonoBehaviour
    {
        public int total = 15;
        public int current = 5;

        public ProgressBarIcon iconPrefab;
        public Transform iconRoot;
        public List<ProgressBarIcon> icons = new();
        
        public RectTransform bgRect;
        public RectTransform barRect;

        private void RefreshBar()
        {
            var pct = (float)current / total;
            barRect.anchorMax = new Vector2(pct, 1);
            foreach (var icon in icons) icon.Refresh();
        }
        
        public void SetCurrentProgress(int progress)
        {
            current = progress;
            RefreshBar();
        }

        public void SetCurrentProgress(int progress, float time)
        {
            StartCoroutine(TweenProgress(progress, time));
        }

        private IEnumerator TweenProgress(int target, float time)
        {
            var currentPct = (float)current / total;
            var targetPct = (float)target / total;
            var stepSize = (targetPct - currentPct) / time;
            var t = 0f;
            while (t < time)
            {
                currentPct += stepSize * Time.deltaTime;
                t += Time.deltaTime;
                barRect.anchorMax = new Vector2(currentPct, 1);
                yield return null;
            }
            current = target;
            RefreshBar();
        }
        
        public void SetTotalProgress(int progress)
        {
            total = progress;
            RefreshBar();
        }

        #if UNITY_EDITOR
        private void OnValidate()
        {
            RefreshBar();
        }
        #endif

        public ProgressBarIcon AddIcon(Sprite icon, int progress)
        {
            var instance = Instantiate(iconPrefab, iconRoot);
            instance.bar = this;
            instance.SetSprite(icon);
            instance.SetProgress(progress);
            instance.Refresh();
            instance.gameObject.SetActive(true);
            icons.Add(instance);
            return instance;
        }

        public void ClearIcons()
        {
            foreach (var icon in icons) Destroy(icon.gameObject);
            icons.Clear();
        }
    }
}